package edu.hcmus.sow.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.domain.Forum;
import edu.hcmus.sow.domain.Topic;

/**
 * DAO to manage Topic entities.
 * 
 */
@Repository("TopicDAO")
@Transactional
public class TopicDAOImpl extends AbstractHibernateDAO<Topic, Integer>
		implements TopicDAO {

   public Topic findByID (Integer id) throws DataAccessException{
      String queryString = "FROM Topic t join fetch t.user WHERE t.id = ?";
      List<Topic> list = executeQuery(queryString, id);
      return list.size() == 0 ? null : list.get(0);
   }
	public int getFormIDByTopicID(Integer topicID) throws DataAccessException {
		String queryString = "select t.forum.id from Topic t WHERE t.id = ?";
		Query query = createQuery(queryString, topicID);
		return (Integer) query.uniqueResult();
	}

	public int getLatestTopic(Forum forum) throws DataAccessException {
		if (getTopicsByForumID(forum).size() > 0) {
			String queryString = "select max(t.id) from Topic t WHERE t.forum = ?";
			Query query = createQuery(queryString, forum);
			return (Integer) query.uniqueResult();
		} else
			return 0;
	}

	public List<Topic> getTopicsByForumID(Forum forum)
			throws DataAccessException {
		String queryString = "FROM Topic t join fetch t.user WHERE t.forum = ?";
		List<Topic> list = executeQuery(queryString, forum);
		return list;
	}

	public int getNumberTopicByForum(Forum forum) throws DataAccessException {

		String queryString = "select count(*) from Topic t WHERE t.forum = ?";
		Query query = createQuery(queryString, forum);
		long count = (Long) query.uniqueResult();
		return (int) count;

	}
}
